package com.etonenet.etpe.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.etonenet.etpe.entity.SpInfo;
import com.etonenet.etpe.repository.SpInfoRepository;
import com.etonenet.taglibs.component.AjaxPage;
import com.etonenet.taglibs.util.AjaxPageUtil;
import com.etonenet.util.TilesUtil;
import com.etonenet.web.PageRequest;
import com.etonenet.web.SpecificationCondition;
import com.etonenet.web.SpecificationHelper;
import com.etonenet.web.UrlConstants;

@RestController
@RequestMapping
public class SpInfoController {
  @Autowired
  private SpInfoRepository spInfoRepository;

  @RequestMapping(UrlConstants.SYSTEM_SPINFO_INDEX)
  public ModelAndView sysSpInfoIndex() {
    ModelAndView mv = new ModelAndView(TilesUtil.getPath(UrlConstants.SYSTEM_SPINFO_INDEX));
    return mv;
  }

  @ResponseBody
  @RequestMapping(UrlConstants.SYSTEM_SPINFO_DATA)
  public AjaxPage sysSpInfoData(Integer pageNumber, Integer pageSize, String spName,
      String sortName, String sortOrder) {
    List<SpecificationCondition> conditions = new ArrayList<>();
    conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("spName", spName));

    SpecificationHelper<SpInfo> sh = new SpecificationHelper<>(conditions, sortOrder, sortName);

    Page<SpInfo> p =
        spInfoRepository.findAll(sh.createSpecification(), new PageRequest(pageNumber, pageSize));
    return AjaxPageUtil.toAjaxPage(p.getTotalElements(), p.getContent());
  }

  @ResponseBody
  @RequestMapping(UrlConstants.SYSTEM_SPINFO_NEW)
  public ModelAndView sysSpInfoNew() {
    ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_SPINFO_NEW);

    return mv;
  }

  @ResponseBody
  @RequestMapping(UrlConstants.SYSTEM_SPINFO_VIEW)
  public ModelAndView sysSpInfoView(Long spId) {
    ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_SPINFO_VIEW);
    mv.addObject("spInfo", spInfoRepository.findOne(spId));

    return mv;
  }

  @ResponseBody
  @RequestMapping(UrlConstants.SYSTEM_SPINFO_UPDATE)
  public String sysSpInfoUpdate(SpInfo spInfo) {
    spInfoRepository.save(spInfo);

    return "修改成功";
  }

  @ResponseBody
  @RequestMapping(UrlConstants.SYSTEM_SPINFO_CREATE)
  public String sysSpInfoData(SpInfo spInfo) {
    spInfoRepository.save(spInfo);

    return "保存成功";
  }
  
  @ResponseBody
  @RequestMapping(UrlConstants.SYSTEM_SPINFO_DEL)
  public String sysSpInfoDel(@RequestBody List<SpInfo> data) {
    spInfoRepository.delete(data);
    
    return "删除成功";
  }
}
